<?php

declare (strict_types=1);

namespace App\Model;

/**
 * @property int $id
 * @property string $currency_code
 * @property string $target_currency_code
 * @property string $exchange_rate
 * @property int $update_time
 */
class ExchangeRate extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'exchange_rate';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['id', 'currency_code', 'target_currency_code', 'exchange_rate', 'update_time'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'update_time' => 'integer'];

    /**
     * @param $userCurrency 转换之后的目标货币
     * @param $currency 被转化的货币
     * @param $price
     * @return float|void
     */
    public static function exchangePrice($userCurrency, $currency, $price)
    {


        // 通货币
        if ($userCurrency == $currency) {
            return $price;
        }

        //都没有美元 进行美元 中转换汇
        if ($userCurrency != 'USD' && $currency != 'USD') {

            // 1 被转货币先转换为美元


            $usdRate = self::where(['currency_code' => $currency])->value('exchange_rate');

            $usdPrice = $usdRate * $price;

            $userRate = self::where(['currency_code' => $userCurrency])->value('exchange_rate');

            return round($usdPrice / $userRate, 2);

        } else {

            if ($currency == 'USD') {
                $rate = self::where(['currency_code' => $userCurrency])->value('exchange_rate');
                return round($price / $rate, 2);
            } elseif ($userCurrency == 'USD') {

                $rate = self::where(['currency_code' => $currency])->value('exchange_rate');
                return round($price * $rate, 2);

            }
        }


    }
}